package dashboard;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.mail.Session;

import com.googlecode.objectify.*;
public class UserRegistry {
	
	private static UserRegistry instance = null;
	private List<User> users;
	private Objectify ofy = ObjectifyService.begin();
	
	public UserRegistry()
	{
		ObjectifyService.register(User.class);
		updateRegistery();
	}
	
	public void updateRegistery()
	{
		users = new ArrayList<User>();
		Iterator<User> it = ofy.query(User.class).fetch().iterator();
		while(it.hasNext())
			users.add(it.next());
	}
	public static UserRegistry getInstance()
	{
		if(instance == null)
		{
			instance = new UserRegistry();
		}
		return instance;
	}
	
	public void addUser(User user)
	{
		ofy.put(user);
		updateRegistery();
	}
		
	public User getUser(String userName)

	{
		for(User user: users)
		{
			if(user.getUserName().equals(userName))
				return user;
		}
		return null;
	}
	public User getUserByUserName(String userName)

	{
		for(User user: users)
		{
			if(user.getUserName().equals(userName))
				return user;
		}
		return null;
	}
	
	public User getUserByNumber(String rNumber){
		for(User user: users)
		{
			if(user.getNumber().equals(rNumber))
				return user;
		}
		return null;
	}
	
	public List<User> getAllUsers(){
		return users;
	}
	
	public void removeUser(User user) 
	{
		ofy.delete(user);
		for(User u: users)
		{
			if(u.getNumber().equals(user.getUserName()))
				users.remove(u);
		}
	}
	
	public User getUserById(long id) 
	{	
		for(User u: users)
		{
			if(u.getId() == id)
				return u;
		}	
		return null;
	}


	public long getUserId(String userName) {
		
		for(User user: users){
			if(user.getUserName().equals(userName)){
				return user.getId();
			}
		}
		return -1;
	}

	public String getUserName(long id) {
		
		for(User user: users){
			if(user.getId() == id){
				return user.getUserName();
			}
		}
		return null;
	}
	
	public boolean emailInUse(String email)
	{
		for(User u: users)
		{
			if(u.getEmail() == email)
				return true;
		}	
		return false;
	}
	}
	

